﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using Moonwish.Core;
using Moonwish.Core.DataAccess;
using Moonwish.SchoolDorms.DataEntity;

namespace Moonwish.SchoolDorms.DataAccess.SqlServer.BuildCmd
{
    public class QueryDataCommand : QueryCommand<V_SCD_Build>
    {
        public QueryDataCommand(DbContext dbContext, Request request) : base(dbContext, request)
        {
            Map.Add("Build.Id".ToLower(), "Build_Id");
            Map.Add("Build.Name".ToLower(), "Name");
        }

        public override List<V_SCD_Build> Execute()
        {
            return DbContext.Set<V_SCD_Build>().SqlQuery(BuildSql()).ToList();
        }

        protected override string BuildSql()
        {
            var sql = new StringBuilder();
            sql.Append("select * from [V_SCD_Build] t where 1 = 1 ");
            if (Request.Items != null)
            {
                foreach (var item in Request.Items)
                {
                    if (String.IsNullOrEmpty(item.FieldName))
                    {
                        throw new InvalidOperationException("查询条件的字段名称不能为空。");
                    }
                    if (item.Values == null || item.Values.Length == 0)
                    {
                        throw new InvalidOperationException("查询条件的值不能为空。");
                    }
                    string column = ToDbColumn(item.FieldName.ToLower());
                    sql.Append(String.Format(" {0} {1} {2} {3} ", item.Relation, column, item.GetOperator(), item.GetValues()));
                }
            }
            return sql.ToString();
        }
    }
}
